package com.copa.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author copa
 * @createDate 2021-09-23 9:05
 * @function 客户端
 */
public class Client {

    public void start(String username) throws IOException {
        // 连接服务器端
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
        // 非阻塞
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 开启线程，接收服务器消息
        // TODO:服务器宕机后客户端应该也要停掉（没弄）
        new Thread(new ClientThread(selector)).start();
        // 输入聊天内容
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            if (msg.length() > 0) {
                socketChannel.write(Charset.forName("UTF-8").encode(username + ":" + msg));
            }

        }
    }

    public static void main(String[] args) throws IOException {
        new Client().start("copa");
    }
}
